package com.ice.config;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Slf4j
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    /*
   此处成员变量应该使用@Value从配置中读取
    */
    private int corePoolSize = 4;
    private int maxPoolSize = 20;
    private int queueCapacity = 2000;
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        log.info("---创建Spring线程池---大小"+maxPoolSize);
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        AsyncUncaughtExceptionHandler asyncUncaughtExceptionHandler = (ex, method, params) -> {
            log.error("Async Exception**************************************************************");
            log.error("method happen: {}", method);
            log.error("method params: {}", params);
            log.error("Exception class: {}", ex.getClass().getName());
            log.error("ex.getMessage(): {}", ex.getMessage());
            log.error("**************************************************************");
        };
        return asyncUncaughtExceptionHandler;
    }

}